<?php
/**
 * 判断登录类
 * 判断是否有session存在，存在则可以登录，否则跳转到登陆页面
 * 
 * @author Lee <a605333742@gmail.com>
 * @time 2016-04-19
 */
namespace Home\Controller;

class AllowController extends EmptyController{
    /*
     *构造函数
     * 用户输入URL的时候判断是否存在$_SESSION['home']['name']，存在则允许跳转到指定url，否则跳转到登录页面
     * 
     * @return # 
     */
    public function _initialize(){
        parent::_initialize();
        $this->examen       =D('Examen');
        $this->answerList   =D('AnswerList');
        $this->notice       =D('Notice');
        $this->data         =D('Data');
        $this->feedback     =D('Feedback');
        $this->activ        =D('Club');
        $this->kpi          =D('Kpi');
        $this->kpiTasks     =D('KpiTasks');
        $this->gClub        =D('ClubGroup');
        $this->db_notice    =D('Notice');
        $this->statistics   =D("Statistics");
        $this->statisticVote=D("StatisticVote");
        $this->drawNum      =D("DrawNum");
        $this->draw_reg     =D("DrawReg");
        $this->DrawData     =D("DrawData");
        
        
        if(!$_SESSION['home']['name']){
            $this ->redirect("Manager/login");
            exit;
        }
        /*正在进行的民意调查 start*/       
        $where=array(
            "status"    =>1,
            "is_examen" =>1
        );
        $examen=$this->examen->where($where)->find();         
        /*查询本人是否参与过该调查，参与则显示比例，没有参与则不显示 start*/
        $map['exa_id']      =$examen['id'];
        $map['assign_id']   =session("home.id");
        if($this->feedback->where($map)->find()){
            $_SESSION['home']['is_examen_ok']   ='ok';
        }
        /*end*/
        /*正在进行的民意调查 end*/
        /*备选答案列表 start*/        
        $where1=array(
            "exa_id"    =>$examen['id'],
            "status"    =>1
        );
        $answerList =$this->answerList->where($where1)->select();
        /*备选答案列表 end*/
        /*答案占比start*/
         $stat_ropo =D("StatisticsRoportion")->where(array("exa_id"=>$examen['id']))->select();
        /*答案占比end*/        
        /*最近的前三条新闻列表 start*/
        $ord1['top']    =desc;
        $where2=array(
            "status"    =>1,
            "sign"      =>3,
        );
        $newsList       =$this->notice->where($where2)->order($ord1)->limit(0,3)->select();        
        /*最近的前三条新闻列表 end*/
        /*最近三条培训资料 start*/        
        $ord2['add_time']   =desc;
        $where3['status']   =1;
        $dList              =$this->data->where($where3)->order($ord2)->limit(0,3)->select();            
        /*最近三条培训资料 end*/
        /*关于本人的最近两条活动 start*/
        $activList  =$this->activ->select();
        $myActivId  =array();
        foreach($activList as $k){
            if(in_array(session("home.id"),  explode(",", $k['activity_ids']))){
                $myActivId[]=$k['id'];
            }
        }
        $where4=array(
            "status"    =>1,
            "id"        =>array("in",implode(",",$myActivId)),
            'validity'  =>array("gt",time())
        );
        $ord3['validity']=asc;
        $myActivList=$this->activ->where($where4)->order($ord3)->limit(2)->select();
        /*关于本人的最近两条活动 end*/
        /*我参与的俱乐部 start*/       
        $clubList1  =$this->gClub->select();
        $myClubIds  =array();
        foreach($clubList1 as $k){
            if(in_array(session("home.id"),  explode(",", $k['user_ids']))){
                $myClubIds[]=$k['id'];
            }
        }
        $where7=array(
            'status'    =>1,
            "id"        =>array("in",  implode(",", $myClubIds))
        );
        $myClubList     =$this->gClub->where($where7)->field("id,name,no_read_ids")->select();
        //判断该俱乐部是否有未读活动
        foreach($myClubList as $k=>$v){
            if(in_array(session("home.id"),explode(",", $myClubList[$k]['no_read_ids']))){
                $myClubList[$k]['no_read']=1;
            }
        }
        /*我参与的俱乐部 end*/
        /*关于本人的最近KIP考核任务 start*/       
        $where5=array(
            "status"    =>1,
            "accept_id" =>$_SESSION['home']['id']
        );
        $ord4['add_time']=desc;
        $kpi_id         =$this->kpi->where($where5)->order($ord4)->limit(1)->find();
        $where6=array(
            "status"    =>1,
            "kpi_id"    =>$kpi_id['id']
        );
        $kpi_stasks     =$this->kpiTasks->where($where6)->select();            
        /*关于本人的最近KIP考核任务 end*/       
       
        $this->assign("myActivList",$myActivList);  //关于本人的最近两条活动
        $this->assign("examen",$examen);            //民意调查问题
        $this->assign("answerList",$answerList);    //民意调查备选答案
        $this->assign("newsList",$newsList);        //最近三条新闻
        $this->assign("dList",$dList);              //最近三条培训列表 
        $this->assign("kpi_stasks",$kpi_stasks);    //最近的本人考核
        $this->assign("myClubList",$myClubList);    //我参与的俱乐部 
        $this->assign("stat_ropo",$stat_ropo);      //调查答案占比
        $this->assign("lang",L());
    }
    
    /*
     * 验证民意调查
     * 
     * @return bool 
     */
    public function ajaxExa(){
        $a  ="";
        $where=array(
            "exa_id"    =>I("post.exa_id","","int"),
            "assign_id" =>I("post.user_id","","int"),
            "status"    =>1
        );
        $is_exist       =$this->feedback->where($where)->find(); 
        if($is_exist!=NUll){
            $this->ajaxReturn(2);
            exit;
        }
        $this->feedback->startTrans();
        $where1=array(
            "exa_id"    =>I("post.exa_id","","int"),
            "assign_id" =>I("post.user_id","","int"),
            "ans_id"    =>I("post.answer_id","","int")
        );
        $inset          =$this->feedback->add($where1);
        if($inset){
            $map['exa_id']          =I("post.exa_id","","int");
            $map['statistics_time'] =time();
            $count_                 =$this->feedback->where(array("exa_id"=>I("post.exa_id","","int"),'status'=>1))->count(); 
            if(!$this->statistics->where(array("exa_id"=>$map['exa_id']))->find()){
                $map['join_num']    =$count_;
                $stat               =$this->statistics->add($map);
            }else{
                $map['join_num']    =$count_;
                $map['id']          =$this->statistics->where(array("exa_id"=>$map['exa_id']))->getField('id');
                $stat               =$this->statistics->save($map);
            }
            if($stat){
                $map1['exa_id']     =I("post.exa_id","","int");
                $map1['ans_id']     =I("post.answer_id","","int");
                $stat_ropo          =D("StatisticsRoportion")->where($map1)->find();
                if($stat_ropo){
                    D("StatisticsRoportion")->where($map1)->setInc('ans_id_num');                    
                    $ansList        =D("StatisticsRoportion")->where(array("exa_id"=>I("post.exa_id","","int")))->select();                    
                    foreach($ansList as $k=>$v){
                        $v['ans_id_roportion']      =round(($v['ans_id_num']/$count_)*100,2)."%";
                        $map2['id']                 =$v['id'];
                        $map2['ans_id_roportion']   =$v['ans_id_roportion'];
                        D("StatisticsRoportion")->save($map2);
                    }
                }else{
                    $map1['ans_id_num'] =1;
                    D("StatisticsRoportion")->add($map1);
                    $ansList            =D("StatisticsRoportion")->where(array("exa_id"=>I("post.exa_id","","int")))->select();
                    foreach($ansList as $k=>$v){
                        $v['ans_id_roportion']      =round(($v['ans_id_num']/$count_)*100,2)."%";
                        $map2['id']                 =$v['id'];
                        $map2['ans_id_roportion']   =$v['ans_id_roportion'];
                        D("StatisticsRoportion")->save($map2);
                    }
                }
                //添加投票次数统计
                if(!$this->addVoteNum()){
                    $this->feedback->rollback();
                    $this->ajaxReturn(3);
                }
                //添加抽奖次数统计
                if(!$this->addDraw(1)){
                    $this->feedback->rollback();
                    $this->ajaxReturn(4);
                }
                $_SESSION['home']['is_examen_ok']   ='ok';
                $this->feedback->commit();
                $a  =1;
            }else{
                $this->feedback->rollback();
                $a  =5;
            }
        }else{
            $this->feedback->rollback();
            $a  =6;
        }
        $this->ajaxReturn($a);
    }
    
    /*
     * 查询首页公告一条
     * 根据不同的页面机型切换，首页，新闻页面，所有页面
     * 
     * @return #
     */
    public function firstInfo($id=''){
         /*查询主页公告（一条） start*/
        $where=array(
            "status"=>1
        );        
        if(C("PAGE_JUMP_PARAM") && C("PAGE_JUMP_PARAM") !=4){
            $where['sign']  =C("PAGE_JUMP_PARAM");
        }else{
            $where['sign']  =array("neq",'3');
        }
        if($id){
            $where['id']    =$id;
        }else{
            $ord['top']         =desc;
            $where['section_id']=1;
        }
        $noticeInfo =M("Notice")->where($where)->order($ord)->find();
        /*点赞数量start*/
        $zanNum     =D("Zambia")->where(array("group_id"=>$noticeInfo['id']))->count();
        /*点赞数量end*/
        $map=array(
            "status"=>1
        );
        if(C("PAGE_JUMP_PARAM")<4){
            $map['sign']    =C("PAGE_JUMP_PARAM");
            $sTop           =M("Notice")->where($map)->max('top');
            if($sTop<$noticeInfo['top']){
                session("top",$noticeInfo['top']);
            }else{
                session("top",$sTop);
            }
        }else{
            $sTop           =M("Notice")->where($map)->max('top');
            session("top",$sTop);
        }
        
        /*查询主页公告（一条） end*/
        if(C("PAGE_JUMP_PARAM")==1){
            $toptitle="Announcements";
        }elseif(C("PAGE_JUMP_PARAM")==2){
            $toptitle="News";
        }else{
            $toptitle="All";
        }
        $this->assign("toptitle",$toptitle);        //顶部
        $this->assign("noInfo",$noticeInfo);        //详细公告
        $this->assign("zan",$zanNum);               //点赞数量
    }
    
    
    /*
     * 语言切换设置
     * 
     * @return #
     */
    public function zh_us(){
        $sign   =I("request.lang");
        if($sign==1){
            session("lang",'1');
        }else if($sign==2){
            unset($_SESSION["lang"]);
        }
        redirect($_SERVER['HTTP_REFERER']);
    }
    
    /*
     * 添加投票次数统计
     * 
     * @return #
     */
    public function addVoteNum(){
        $map['user_id'] =session("home.id");
        $map['add_time']=array("LIKE","%".trim(date("Y-m-d",time()))."%");
        if($this->statisticVote->where($map)->find()){
            //如果本月的投票次数存在，则增加
            if($this->statisticVote->where($map)->setInc('num')){
                return TRUE;
            }else{
                return FALSE;
            }
        }else{
            //如果本月的投票次数不存在则新增
            $map['num'] =1;
            if($this->statisticVote->add($map)){
                return TRUE;
            }else{
                return FALSE;
            }
        }
    }
    
    /*
     * 添加抽奖次数统计
     * 
     * @return bool
     */
    public function addDraw($from_type=0){
        $map['user_id']     =session('home.id');
        $map['from_type']   =$from_type;
        $map['draw_num']    =time();
        if($this->drawNum->add($map)){
            return TRUE;
        }else{
            return FALSE;
        }        
    }
    
    /*
     * 抽奖
     * 
     * @return #
     */
    public function do_draw(){ 
        //查询改约是否有抽奖
        $date       =date("Y-m",time());
        //查询上次的要将记录，如果上次摇奖流程没有完成，清空上次的参奖人员真资格（例：上次摇奖一等奖，没有进行二三等奖的摇奖，为避免上次参奖人员影响本次摇奖，需清空上次参奖人员）
        $lastdate   =date("Y-m-d",time());
        $lastmap    =array(
            'add_time'  =>array("NOTLIKE","%".$lastdate."%")
        );
        
        $this->DrawData->startTrans();
        $lastDrawTime   =$this->draw_reg->where($lastmap)->order("id desc")->getField("add_time");
        
        if($lastDrawTime){
            //清空上次摇奖时间以前的摇奖人资格
            $map1['add_time']   =array("elt",$lastDrawTime);
            $map1['status']     =0;
            if(!$this->drawNum->save($map1)){
                echo FALSE;exit;
            }
        }
        $is_draw=$this->draw_reg->where(array('add_time'=>array("LIKE","%".$date."%")))->find(); 
        //有资格参与摇奖人的id
        $ids    =$this->drawNum->where(array("status"=>1))->field('user_id')->select();
        $justOne=array();       //参奖人id集合
        foreach($ids as $vo){
            $justOne[]  =$vo['user_id'];
        }
        if($is_draw){
            //如果存在，则说明摇奖等级为二等奖或三等奖
            if($is_draw['draw_num']==1){
                //一等奖已开，该次摇奖为二等奖
                //去除一等奖的幸运儿
                $twoDraw=array();
                foreach($justOne as $vo){
                    if($vo!=session('draw_one')){
                        $twoDraw[]  =$vo;
                    }
                }
                //摇奖
                $drawGog    =array();
                for($i=0;$i<5;$i++){
                    $userId     =$twoDraw[array_rand($twoDraw,1)];
                    $drawGog[$i]=$userId;
                    foreach($twoDraw as $k=>$v){
                        if($v==$userId){
                            unset($twoDraw[$k]);
                        }
                    }
                }
                /*
                //摇奖
                $drawGogKey =array_rand($twoDraw,5);
                $drawGog    =array();
                
                //将中奖人的id建明转为键值（即转为user_id）
                foreach($drawGogKey as $voVal){
                    $drawGog[]  =$twoDraw[$voVal];
                }
                 * 
                 */
                //修改摇奖记录
                $map3['id']         =$is_draw['id'];
                $map3['draw_num']   =2;
                if(!$this->draw_reg->save($map3)){
                    $this->DrawData->rollback();
                    echo FALSE;exit;
                }
                //将中奖信息写入获奖记录
                $userName   =array();
                foreach($drawGog as $vo){
                    $map4['user_id']    =$vo;
                    $map4['draw_grade'] =2;
                    //将中奖人id转为人名
                    $userName[] =getUsername($vo);
                    if(!$this->DrawData->add($map4)){
                        $this->DrawData->rollback();
                        echo FALSE;
                        break;
                    }
                }
                $drawGog[]=session("draw_one");
                session('draw_two',$drawGog);
                //echo array("sign"=>2,"name"=>$userName);
                echo "二等奖幸运用户\n".implode("\n", $userName);
            }else if($is_draw['draw_num']==2){
                //二等奖已开，此次摇奖为三等奖
                //去除一等奖二等奖的幸运儿
                $threeDraw=array_diff($justOne,session('draw_two'));
                //摇奖
                $threeDrawGog   =array();
                for($i=0;$i<8;$i++){
                    $userId             =$threeDraw[array_rand($threeDraw,1)];
                    $threeDrawGog[$i]   =$userId;
                    foreach($threeDraw as $k=>$v){
                        if($v==$userId){
                            unset($threeDraw[$k]);
                        }
                    }
                }
                /*
                //摇奖
                $threeDrawGogKey=array_rand($threeDraw,8);
                $threeDrawGog   =array();
                foreach($threeDrawGogKey as $voVal){
                    $threeDrawGog[] =$threeDraw[$voVal];
                }
                 * 
                 */
                //修改摇奖记录
                $map5['id']         =$is_draw['id'];
                $map5['draw_num']   =3;
                if(!$this->draw_reg->save($map5)){
                    $this->DrawData->rollback();
                    echo FALSE;exit;
                }
                //将中将详细写入中奖纪录
                $userName   =array();
                foreach($threeDrawGog as $vo){
                    $map6['user_id']    =$vo;
                    $map6['draw_grade'] =3;
                    //将中奖人id转为人名
                    $userName[] =getUsername($vo);
                    if(!$this->DrawData->add($map6)){
                        $this->DrawData->rollback();
                        echo FALSE;
                        break;
                    }
                }                
                //摇奖结束，清空数据
                $map7['status']     =0;
                if(!$this->drawNum->where(array("draw_num"=>array("elt",strtotime($is_draw['add_time']))))->save($map7)){
                    $this->DrawData->rollback();
                    echo FALSE;exit;
                }
                echo "三等奖幸运用户\n".implode("\n", $userName);
            }else if($is_draw['draw_num']==3){
                //摇奖结束
                echo "本次摇奖结束 : )";exit;
            }
        }else{
            //如果不存在，则说明是首次摇奖，摇奖为一等奖，人数为一人            
            //echo $justOne[array_rand($justOne,1)];
            //将一等奖信息加入摇奖记录
            $map['deaw_user_id']    =session('home.id');
            $draw_reg   =$this->draw_reg->add($map);
            //将一等奖中奖信息加入获奖记录
            $map2['user_id']    =$justOne[array_rand($justOne,1)];
            $map2['draw_grade'] =1;
            $draw_data          =$this->DrawData->add($map2);
            if($draw_reg && $draw_data){
                $this->DrawData->commit();
                session("draw_one",$map2['user_id']);
                echo "一等奖幸运用户\n　　".getUsername($map2['user_id']);
            }else{
                $this->DrawData->rollback();
                echo '参数错误，抽奖失败';exit;
            }
        }
    }
}
